package org.gd.hellomysql;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

public abstract class MySQLConnectionFactory extends ConnectionFactory {

    private final static String host = "localhost";
    private final static Integer port = 3306;
    private final static String login = "root";
    private final static String password = "root";
    private final static String driverPath = com.mysql.jdbc.Driver.class.getName();
    private static boolean driverIsFind = false;

    private static String getUrl(String dbName) {
        return String.format("jdbc:mysql://%s:%d/%s", host, port, dbName);
    }

    public static Connection getConnection()
            throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        return getConnection("");
    }

    public static Connection getConnection(String dbName)
            throws SQLException {
        try {
            Enumeration<Driver> drivers = DriverManager.getDrivers();
            while (drivers.hasMoreElements()) {
                Driver driver = drivers.nextElement();
                if(driver.getClass().equals(com.mysql.jdbc.Driver.class)) {
                    driverIsFind = true;
                    break;
                }
            }
            if(!driverIsFind) {
                DriverManager.registerDriver((Driver) Class.forName(driverPath).newInstance());
            }
            Connection conn = DriverManager.getConnection(getUrl(dbName), login, password);
            if(conn == null) {
                throw new SQLException("connection is null");
            }
            return conn;
        } catch (InstantiationException e) {
            throw new MySQLException(e);
        } catch (IllegalAccessException e) {
            throw new MySQLException(e);
        } catch (ClassNotFoundException e) {
            driverIsFind = false;
            throw new MySQLException(e);
        }
    }
}
